﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Holidays.CountryCalculators {

	public class DanishCalculator : BaseCalculator {

		public override Boolean IsWeekend(DateTime date) {
			return date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday;
		}

		/// <summary>
		/// In Denmark a vacation year is from May to May.
		/// </summary>
		/// <param name="date"></param>
		/// <returns></returns>
		public override Int32 VacationYear(DateTime date) {
			if (date.Month < 5) {
				return date.Year - 1;
			}
			return base.VacationYear(date);
		}

		protected override Boolean IsDynamicHoliday(DateTime date, XDocument holidayData) {
			Dictionary<String, DateTime> baseDates = this.GetBaseDates(holidayData, date);
			IEnumerable<XElement> dates = holidayData.Root.Elements("Date")
											.Where(d =>
												d.Attribute("Type").Value == "dynamic" &&
												(d.Attribute("StartYear") == null || Int32.Parse(d.Attribute("StartYear").Value) <= date.Year) &&
												(d.Attribute("EndYear") == null || Int32.Parse(d.Attribute("EndYear").Value) >= date.Year) &&
												d.Attribute("Holiday").Value == "true"
											);
			foreach (XElement day in dates) {
				Int32 delta;
				if (Int32.TryParse(day.Attribute("DeltaDay").Value, out delta)) {
					if (baseDates.ContainsKey(day.Attribute("Base").Value)) {
						DateTime baseDate = baseDates[day.Attribute("Base").Value];
						if (baseDate.AddDays(delta) == date) {
							return true;
						}
					}
				}
			}
			return false;
		}
	}
}